package command

import (
	"encoding/json"
	"fmt"
	"gitee.com/csingo/cContext"
	"gitee.com/csingo/cHelper"
	"gitee.com/csingo/cLog"
	"io/fs"
	"io/ioutil"
	"path/filepath"
	"satis-go/base/collector"
	"satis-go/config/vars"
	"strings"
)

type PackagesJsonCommand struct{}

func (i *PackagesJsonCommand) CommandName() (app, name string) {
	return "collector", "PackagesJsonCommand"
}

func (i *PackagesJsonCommand) Create() {
	ctx := cContext.New()
	pkgs := &collector.Packages{
		Packages: []string{},
		Includes: map[string]map[string]string{},
	}
	includeDir := filepath.Clean(fmt.Sprintf("%s/include", vars.CollectorConfig.PackagesPath))
	if !cHelper.IsExistsPath(includeDir) {
		return
	}
	err := filepath.Walk(includeDir, func(fPath string, info fs.FileInfo, err error) error {
		if info.IsDir() {
			return err
		}

		content, err := ioutil.ReadFile(fPath)
		if err != nil {
			cLog.WithContext(ctx, map[string]interface{}{
				"fPath": fPath,
			}).Error("读取include文件异常")
			return err
		}

		sha1Res := cHelper.SHA1(string(content))
		relativePath := strings.TrimPrefix(filepath.Clean(fPath), filepath.Clean(vars.CollectorConfig.PackagesPath))
		relativePath = strings.ReplaceAll(relativePath, "\\", "/")
		relativePath = strings.Trim(relativePath, "/")
		pkgs.Includes[relativePath] = map[string]string{
			"sha1": sha1Res,
		}

		return err
	})
	if err != nil {
		cLog.WithContext(ctx, map[string]interface{}{
			"dir": includeDir,
		}).Error("遍历include目录生成packages.json异常")
	}
	// 写packages.json
	pkgsJsonBody, err := json.Marshal(pkgs)
	if err != nil {
		cLog.WithContext(ctx, map[string]interface{}{
			"pkgs": pkgs,
		}).Error("packages.json格式化失败")
		return
	}

	pkgsPath := filepath.Clean(fmt.Sprintf("%s/packages.json", vars.CollectorConfig.PackagesPath))
	err = ioutil.WriteFile(pkgsPath, pkgsJsonBody, 0755)
	if err != nil {
		cLog.WithContext(ctx, map[string]interface{}{
			"pkgs": pkgs,
			"path": pkgsPath,
		}).Error("packages.json写文件失败")
	}
}
